﻿using MvvmCross.Core.ViewModels;
using Sidvall.UI.Dialogs;
using Sidvall.UI.Entities;
using Sidvall.UI.ViewModels;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Sidvall.UI.Wpf.ViewModels
{
    public class StartViewModel : Sidvall.UI.ViewModels.ViewModelBase
    {
        #region Public Members

        #region ResourceCollectionManager

        private Sidvall.UI.Wpf.Resources.ResourceCollectionManager _ResourceCollectionManager;
        public Sidvall.UI.Wpf.Resources.ResourceCollectionManager ResourceCollectionManager
        {
            get
            {
                if (_ResourceCollectionManager == null)
                    this.ResourceCollectionManager = new Sidvall.UI.Wpf.Resources.ResourceCollectionManager();
                return _ResourceCollectionManager;
            }
            set
            {
                _ResourceCollectionManager = value;
                RaisePropertyChanged(nameof(ResourceCollectionManager));
            }
        }

        #endregion
        #region TreeControlViewModel

        private TreeControlViewModel _TreeControlViewModel;
        public TreeControlViewModel TreeControlViewModel
        {
            get
            {
                return _TreeControlViewModel;
            }
            set
            {
                _TreeControlViewModel = value;
                RaisePropertyChanged(nameof(TreeControlViewModel));
            }
        }

        #endregion

        // Commands
        #region OpenFileDialog1Command

        public ICommand OpenFileDialog1Command
        {
            get
            {
                return new MvxCommand(async () => await OpenFileDialog1Async());
            }
        }

        #endregion
        #region OpenFileDialog1Async

        public async Task OpenFileDialog1Async()
        {
            await OpenFileDialogAsync(SystemContext.Current.FileDialog1);
        }

        #endregion
        #region OpenFileDialog2Command

        public ICommand OpenFileDialog2Command
        {
            get
            {
                return new MvxCommand(async () => await OpenFileDialog2Async());
            }
        }

        #endregion
        #region OpenFileDialog2Async

        public async Task OpenFileDialog2Async()
        {
            await OpenFileDialogAsync(SystemContext.Current.FileDialog2);
        }

        #endregion
        #region OpenFileDialogAsync

        public async Task OpenFileDialogAsync(IFileDialog fileDialog)
        {
            DialogManager dialogManager;
            OpenFileDialogContext context;

            using (var busyManager = new Sidvall.Data.BusyManager(this))
            {
                context = new OpenFileDialogContext();
                dialogManager = new DialogManager(fileDialog, null, null, null, null, null, null);
                var name = await dialogManager.OpenFileAsync(context);
                if (!string.IsNullOrWhiteSpace(name))
                    await Sidvall.UI.SystemContext.Current.DialogManager.ShowMessageAsync("Fil", name, MessageType.Information);
            }
        }

        #endregion
        #region CopyFileDialogCommand

        public ICommand CopyFileDialogCommand
        {
            get
            {
                return new MvxCommand(async () => await CopyFileDialogAsync());
            }
        }

        #endregion
        #region CopyFileDialogAsync

        public async Task CopyFileDialogAsync()
        {
            Task task = null;
            bool launchFile = true;
            try
            {
                var context = ProgressDialogContext.NewFileProgressDialogContext("Copy File");
                context.CloseWhenFinished = false;
                var serverStorageManager = new Sidvall.IO.StorageManager(new Sidvall.IO.NetFileSystem()
                {
                    StoreId = "1",
                    BaseAddress = "http://localhost:49446/",
                    //BaseAddress = "http://localhost.fiddler:49446/",
                    AuthenticationStrategy = null,
                    UsePost = true,
                });
                var source = @"1\1\1\anders.jpg";
                var destination = Sidvall.SystemContext.Current.SystemStorageManager.GetTemporaryFilePath(".jpg");
                context.Tasks.Add(new Sidvall.Tasks.CopyFileTask(serverStorageManager, source, Sidvall.SystemContext.Current.SystemStorageManager, destination));

                //source = @"C:\Users\anders0763\Documents\Kod\a.msi";
                //destination = @"a2.msi";
                //context.Tasks.Clear();
                //context.Tasks.Add(new Sidvall.Tasks.CopyFileTask(Sidvall.SystemContext.Current.SystemStorageManager, source, serverStorageManager, destination));
                //launchFile = false;

                var result = await Sidvall.UI.SystemContext.Current.DialogManager.ShowProgressDialogAsync(context);
                if ((launchFile) && (result.Status == Tasks.TaskStatus.RanToCompletion))
                    await Sidvall.SystemContext.Current.LauncherManager.LaunchFileAsync(destination);
                //await Sidvall.UI.SystemContext.Current.DialogManager.ShowMessageAsync("Result", result.Status.ToString(), MessageType.Information);
            }
            catch (System.Exception ex)
            {
                task = Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync("Unexpected Error", ex);
            }
            if (task != null)
                await task;
        }

        #endregion

        #region StartAsync

        protected override async Task StartAsync()
        {
            TreeItem parent;
            var treeItems = new TreeItemCollection();
            var rootPath = @"D:\CodePlex\sidvall\Source\Sidvall.Net.Sms";
            var folders = await Sidvall.SystemContext.Current.SystemStorageManager.GetFolderNamesAsync(rootPath, null, IO.SearchOption.AllDirectoriesIgnoreSecurityExceptions);
            var of = (from o in folders
                      orderby o
                      select o);
            foreach (var item in of)
            {
                var path = item.Substring(rootPath.Length).Trim('\\');
                var name = System.IO.Path.GetFileName(path);
                var parentId = System.IO.Path.GetDirectoryName(path);
                var treeitem = new TreeItem()
                {
                    Id = path,
                    Name = name,
                    FullName = path,
                };
                if (!string.IsNullOrWhiteSpace(parentId))
                    parent = Sidvall.UI.Entities.TreeManager.FindItem(treeItems, parentId);
                else
                    parent = null;
                if (parent != null)
                {
                    treeitem.ParentId = parent.Id;
                    parent.ChildItems.Add(treeitem);
                }
                else
                {
                    treeItems.Add(treeitem);
                }
            }
            treeItems[0].IsVisible = false;
            var treeControlViewModel = new TreeControlViewModel()
            {
                TreeItems = treeItems,
                AllowMultipleSelections = true,
                OnlyAllowChildSelection = false,
                ExpandAllNodes = true,
                SelectedBehavior = Sidvall.UI.Entities.TreeItemSelectedBehavior.PropagateDownAndUp,
            };
            treeControlViewModel.Initialize();
            this.TreeControlViewModel = treeControlViewModel;
        }

        #endregion

        #endregion
    }
}
